// 顶点着色器
import { getWebGLContext, initShaders } from '../../../src/lib/cuon-utils';

const VSHADER_SOURCE = `
    attribute vec4 a_Position;
    uniform mat4 u_xFormMatrix;
    void main() {
        gl_Position = u_xFormMatrix * a_Position;
    }`;
// 片元着色器
const FSHADER_SOURCE = `
    void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);   
    }`;
// 旋转角度
let ANGLE = 90.0;

function main() {
    const canvas = document.getElementById('webgl');
    const gl = getWebGLContext(canvas);
    if (!gl) {
        console.log('Failed to get the rendering context for WebGL');
        return;
    }
    if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('Failed to initialize shaders.');
        return;
    }
    // 将顶点位置写入顶点着色器
    const n = initVertexBuffers(gl);
    if (n < 0) {
        console.log('Failed to set the positions of the vertices.');
        return;
    }

    // 创建一个旋转矩阵
    const radian = Math.PI * ANGLE / 180.0; // 转换为弧度
    const cosB = Math.cos(radian), sinB = Math.sin(radian);
    // 注意：WebGL中矩阵是列主序的
    /**
     *  数学中矩阵排列
     *  cosB   -sinB   0    0
     *  sinB   cosB    0    0
     *  0      0       1    0
     *  0      0       0    1
     */
    const xFormMatrix = new Float32Array([
        cosB, sinB, 0.0, 0.0,
        -sinB, cosB, 0.0, 0.0,
        0.0, 0.0, 1.0, 0.0,
        0.0, 0.0, 0.0, 1.0
    ]);

    // 将旋转矩阵传输给顶点着色器
    const u_xFormMatrix = gl.getUniformLocation(gl.program, 'u_xFormMatrix');
    if (!u_xFormMatrix) {
        console.log('Failed to get the storage location of u_xFormMatrix.');
        return;
    }
    gl.uniformMatrix4fv(u_xFormMatrix, false, xFormMatrix);
    // 使用指定颜色清除画布
    gl.clearColor(0, 0, 0, 1);
    // 清除画布
    gl.clear(gl.COLOR_BUFFER_BIT);
    // 绘制三角形
    gl.drawArrays(gl.TRIANGLES, 0, n);
}

function initVertexBuffers(gl) {
    const vertices = new Float32Array([
        0, 0.5, -0.5, -0.5, 0.5, -0.5
    ]);
    const n = 3;
    const vertexBuffer = gl.createBuffer();
    if (!vertexBuffer) {
        console.log('Failed to create the buffer object.');
        return false;
    }

    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

    const a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    if (a_Position < 0) {
        console.log('Failed to get the storage location of a_Position.');
        return -1;
    }
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(a_Position);

    return n;
}

main();
